<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="映射关系id" prop="mapTypeId">
        <el-input
          v-model="queryParams.mapTypeId"
          placeholder="请输入映射关系id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="映射键" prop="dataKey">
        <el-input
          v-model="queryParams.dataKey"
          placeholder="请输入映射键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="映射值" prop="dataValue">
        <el-input
          v-model="queryParams.dataValue"
          placeholder="请输入映射值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签" prop="label">
        <el-input
          v-model="queryParams.label"
          placeholder="请输入标签"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表格类型" prop="secondLevel">
        <el-input
          v-model="queryParams.secondLevel"
          placeholder="请输入表格类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['live:MapRelation:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['live:MapRelation:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['live:MapRelation:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['live:MapRelation:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" plain icon="el-icon-upload" @click="daoru"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="MapRelationList"
      @selection-change="handleSelectionChange"
      :height="650"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="映射关系id" align="center" prop="mapTypeId" />
      <el-table-column
        label="映射关系类型"
        align="center"
        prop="mapRelationType"
      />
      <el-table-column label="映射键" align="center" prop="dataKey" />
      <el-table-column label="映射值" align="center" prop="dataValue" />
      <el-table-column label="标签" align="center" prop="label" />
      <el-table-column label="表格类型" align="center" prop="secondLevel" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['live:MapRelation:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['live:MapRelation:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改映射关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="映射关系id" prop="mapTypeId">
          <el-input v-model="form.mapTypeId" placeholder="请输入映射关系id" />
        </el-form-item>
        <el-form-item label="映射键" prop="dataKey">
          <el-input v-model="form.dataKey" placeholder="请输入映射键" />
        </el-form-item>
        <el-form-item label="映射值" prop="dataValue">
          <el-input v-model="form.dataValue" placeholder="请输入映射值" />
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="表格类型" prop="secondLevel">
          <el-input v-model="form.secondLevel" placeholder="请输入表格类型" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
    <el-dialog
      title="导入"
      :visible.sync="dialogVisible"
      width="500px"
      append-to-body
      v-if="dialogVisible"
    >
      <!-- 文件上传-->
      <el-form
        :rules="rules"
        :model="dataForm"
        ref="dataForm"
        label-width="150px"
        @submit.native.prevent
      >
        <el-form-item label="表格类型" prop="name">
          <!-- <el-input
            type="text"
            v-model.trim="dataForm.name"
            clearable
          ></el-input> -->
          <el-select v-model="dataForm.name" placeholder="表格类型" clearable>
            <el-option
              v-for="dict in secondLevelList"
              :key="dict"
              :label="dict"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="映射类型id" prop="mapTypeId">
          <el-input
            type="text"
            v-model.trim="dataForm.mapTypeId"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="映射类型名" prop="mapRelationType">
          <el-input
            type="text"
            v-model.trim="dataForm.mapRelationType"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="文件：" prop="file">
          <el-upload
            class="upload-import"
            ref="uploadImport"
            :http-request="httpRequest"
            action=""
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="1"
            :on-change="handleChange"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload"
          >
            <!--
            accept="application/zip,.zip" 设置接收的文件类型-->
            <el-button
              v-show="!hasFile"
              slot="trigger"
              size="small"
              type="primary"
              >选取文件</el-button
            >
            <!-- <div slot="tip" class="el-upload__tip">
          只能上传zip文件，且不超过10M
        </div> -->
          </el-upload>
          <!-- 关闭自动上传-->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUpload">提交</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="匹配"
      :visible.sync="openForm"
      width="700px"
      append-to-body
      v-if="openForm"
      @handleColse="handleColse"
    >
      <div class="el-dialog-div">
        <el-form
          :model="noticForm"
          ref="noticForm"
          label-width="100px"
          :inline="true"
          :rules="rules"
        >
          <el-row
            v-for="(noticItem, index) in noticForm.noticConfig"
            :key="index"
          >
            <el-col
              :span="20"
              v-for="nameItem in noticItem.name"
              :key="nameItem.key"
            >
              <el-form-item prop="dataValue" label="">
                <el-input placeholder="显示字段" v-model="nameItem.dataValue">
                </el-input>
                <!--@change="changedemo"
                       <el-select
                      v-model="nameItem.productNo"
                      clearable
                      filterable
                      remote
                      :remote-method="getDatas"
                      :loading="loading"
                      placeholder="合作款式"
                      @change="testProductNo"
                      style="width: 150px"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item"
                        :label="item"
                        :value="item"
                      >
                      </el-option>
                    </el-select> -->
              </el-form-item>
              <el-form-item prop="dataKey" label="">
                <el-select
                  v-model="nameItem.dataKey"
                  clearable
                  filterable
                  placeholder="赋值的字段"
                >
                  <el-option
                    v-for="item in ColorLike"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <!-- <el-button
                    type="primary"
                    size="mini"
                    @click="addDomain(noticItem)"
                    >新增</el-button
                  > -->
              <el-button
                type="danger"
                size="mini"
                @click.prevent="removeDomain(noticItem)"
                >删除</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitlive">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMapRelation,
  getMapRelation,
  delMapRelation,
  addMapRelation,
  updateMapRelation,
  addList,
} from "@/api/live/MapRelation";
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  name: "MapRelation",
  data() {
    return {
      noticForm: {
        noticConfig: [],
      },
      ColorLike: [],
      openForm: false,
      dataForm: {
        name: "达播订单表",
        file: null,
        mapTypeId: 5,
        mapRelationType: "抖音直播映射",
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { max: 50, message: "最长可输入50个字符", trigger: "blur" },
          // { validator: isvalidatName, trigger: "blur" },
        ],
        file: [{ required: true, message: "请选择上传文件", trigger: "blur" }],
      },
      hasFile: false,
      fileList: [],
      dialogVisible: false,
      pjtUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 映射关系表格数据
      MapRelationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mapTypeId: null,
        mapRelationType: null,
        dataKey: null,
        dataValue: null,
        label: null,
        secondLevel: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mapTypeId: [
          { required: true, message: "映射关系id不能为空", trigger: "blur" },
        ],
      },
      secondLevelList: ["达播订单表", "直播订单表"],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }

      return isLt2M;
    },
    handleRemove(file, fileList) {
      if (!fileList.length) {
        this.hasFile = false;
      }
      this.dataForm.file = null;
    },
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
    },
    //确定按钮
    //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
    submitUpload() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$refs.uploadImport.submit();
        }
      });
    },
    httpRequest(param) {
      if (this.dataForm.name.length < 3) {
        this.$modal.msgWarning("请选择到店铺");
        return;
      }
      let fd = new FormData();
      fd.append("file", param.file); // 传文件
      fd.append("secondLevel", this.dataForm.name);
      fd.append("mapTypeId", this.dataForm.mapTypeId);
      fd.append("mapRelationType", this.dataForm.mapRelationType);
      //dataPar.file.raw
      console.log(JSON.stringify(fd));
      this.openLoading();
      axios
        .post(
          process.env.VUE_APP_BASE_API + "/live/MapRelation/propertyMap",
          fd,
          {
            headers: {
              header: { responseType: "blob" },

              Authorization: "Bearer " + getToken(),
              "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // timeout: 20000,
          }
        )
        .then((response) => {
          console.log(response);
          if (response.data) {
            this.dialogVisible = false;
            this.$modal.closeLoading();
            this.$modal.msgSuccess("导入成功");
            this.hasFile = false;
            this.ColorLike = response.data.excelPropertyList;
            this.addDomin(response.data.mapRelationList);
          }
        });
    },
    addDomin(mapRelationList) {
      this.noticForm.noticConfig = [];
      mapRelationList.forEach((item) => {
        this.noticForm.noticConfig.push({
          name: [
            {
              ...item,
            },
          ],
        });
      });
      this.openForm = true;
    },
    removeDomain(item) {
      var index = this.noticForm.noticConfig.indexOf(item);
      this.noticForm.noticConfig.splice(index, 1);
    },
    submitlive() {
      var apply = this.noticForm.noticConfig.map((item) => item.name[0]);
      var live = [];
      apply.forEach((item) => {
        live.push({ ...item });
      });
      addList(live).then((response) => {
        console.log(JSON.stringify(response));
        if (response.code == 200) {
          this.$modal.msgSuccess("提交成功");
        }
        this.openForm = false;
        this.getList();
        this.noticForm.noticConfig = [];
      });
    },
    handleColse() {
      this.openForm = false;
      this.getList();
      this.noticForm.noticConfig = [];
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在导入，请稍候！");
    },
    /** 查询映射关系列表 */
    getList() {
      this.loading = true;
      listMapRelation(this.queryParams).then((response) => {
        this.MapRelationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mapTypeId: null,
        mapRelationType: null,
        dataKey: null,
        dataValue: null,
        label: null,
        secondLevel: null,
        status: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加映射关系";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMapRelation(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改映射关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMapRelation(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMapRelation(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除映射关系编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMapRelation(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "live/MapRelation/export",
        {
          ...this.queryParams,
        },
        `MapRelation_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
